package com.app.admin.controller;

import com.app.admin.service.SystemSettingService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.Map;

@Controller
@RequiredArgsConstructor
@RequestMapping("/api/settings")
public class SystemSettingController {
    private SystemSettingService settingService;

    // 展示系统设置页面
    @GetMapping
    public String showSettings(Model model) {
        // 将所有配置放入模型，前端通过key获取值
        Map<String, String> settings = settingService.getAllSettings();
        model.addAttribute("settings", settings);
        return "system/settings"; // 对应 Thymeleaf 模板路径
    }

    // 保存系统设置
    @PostMapping
    public String saveSettings(@RequestParam Map<String, String> settings,
                               RedirectAttributes redirectAttributes) {
        try {
            settingService.batchUpdateSettings(settings);
            redirectAttributes.addFlashAttribute("successMsg", "配置保存成功！");
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("errorMsg", "配置保存失败：" + e.getMessage());
        }
        return "redirect:/settings"; // 重定向避免表单重复提交
    }
}
